import { defineStore } from 'pinia';
import { useMenuStore } from './menu';
import { useAuthStore } from '@/plugins';
import { useLoadingStore } from './loading';
import { watch } from 'vue';
import { CookieService } from '@/utils/cookie.service';
import { API } from '@/api/api';
// import { API } from '@/api';

export interface Profile {
  account: Account;
  permissions: string[];
  role: string;
}
export interface Account {
  username: string;
  avatar: string;
  gender: number;
}

export type TokenResult = {
  token: string;
  expires: number;
};

export const useAccountStore = defineStore('account', {
  state() {
    return {
      account: {} as Account,
      permissions: [] as string[],
      role: '',
      logged: true,
    };
  },
  actions: {
    login(username: string, password: string) {
      return new Promise<TokenResult>((resolve, reject) => {
        API.Mutation.login({ email: username, password }, ['token', 'expires'])
          .then(async (response) => {
            if (response) {
              const data: TokenResult = {
                token: response.token,
                expires: response.expires,
              }
              CookieService.ins().setUserToken(data.token);
              await useMenuStore().getMenuList();
              resolve(data);
            } else {
              reject(response);
            }
          });
      });
    },
    async logout() {
      return new Promise<boolean>((resolve) => {
        localStorage.removeItem('stepin-menu');
        this.logged = false;
        resolve(true);
      });
    },
    async profile() {
      const { setAuthLoading } = useLoadingStore();
      setAuthLoading(true);
      return new Promise<Profile>((resolve, reject) => {
        API.Query.account(["_id", "username", "avatar", "gender"]).then((account) => {
          if (account) {
            const { setAuthorities } = useAuthStore();
            this.account = {
              username: account.username,
              avatar: account.avatar,
              gender: account.gender,
            };
            this.permissions = ['menu:edit', 'menu:delete', 'menu:add', "menu:list"];
            this.role = 'admin';
            setAuthorities(this.permissions);
            setAuthLoading(false)
            const data = { account: this.account, permissions: this.permissions, role: this.role };
            return resolve(data);
          } else {
            setAuthLoading(false)
            return reject(account);
          }
        });
      });
    },
    setLogged(logged: boolean) {
      this.logged = logged;
    },
  },
});
